package com.durian.base.rxhttp.param

import com.durian.base.net.Utils
import com.durian.base.rxhttp.RxHttp
import com.durian.base.rxhttp.download.DownloadOffSize
import com.durian.base.rxhttp.download.RangeHeader
import okhttp3.Request
import okhttp3.RequestBody
import java.io.UnsupportedEncodingException
import java.net.URLEncoder

/**
 * 说明：RxNobodyParam
 * <p/>
 * 作者：Fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2020/04/24 20:37
 * <p/>
 * 版本：version 1.0
 */
class RxNobodyParam(url: String, method: Method) : RxBaseParam<RxNobodyParam>(url, method), RangeHeader {
    override fun getRequestBody(): RequestBody? {
        return null
    }
    override fun buildRequest(): Request {
        if (isAssemblyEnable) {
            RxHttp.getParamAssembly()?.invoke(this)
        }
        mutableMapOf<String,String>().let {map ->
            paramsBuilder.forEach { map[it.key] = it.value.toString() }
            RxHttp.getRequestBodyHook()?.invoke(this,map)
        }
        val builder = requestBuilder.headers(headersBuilder.build())
                .url(getFullUrl(RxHttp.getHttpUrl(url)))
        when {
            method.isGet() -> {
                builder.get()
            }
            method.isHead() -> {
                builder.head()
            }
            else -> {
                throw IllegalArgumentException("This method(${method}) not support!!!")
            }
        }
        return builder.build()
    }

    private fun String.utf8Encoder(): String {
        try {
            return URLEncoder.encode(this, "UTF-8")
        } catch (e: UnsupportedEncodingException) {
            Utils.eLog(e)
        }
        return ""
    }

    private fun getFullUrl(url: String): String {
        val urlFull = StringBuffer()
        urlFull.append(url)
        if (paramsBuilder.isNotEmpty()){
            if (urlFull.indexOf("?",0) < 0){
                urlFull.append("?")
            }else{
                if (!urlFull.endsWith("&")){
                    urlFull.append("&")
                }
            }
            var flag = 0
            paramsBuilder.forEach {
                urlFull.append(it.key).append("=").append(if (it.isEncoded) it.value.toString().utf8Encoder() else it.value.toString())
                if (++flag != paramsBuilder.size) {
                    urlFull.append("&")
                }
            }
        }
        return urlFull.toString()
    }

    /**
     * 设置断点下载范围
     * 注：
     * 1、开始位置小于0，及代表下载完整文件
     * 2、结束位置要大于开始位置，否则结束位置默认为文件末尾
     * @param startIndex 开始位置
     * @param endIndex   结束位置
     * @return Param
     */
    override fun setRangeHeader(
        startIndex: Long,
        endIndex: Long,
        connectLastProgress: Boolean
    ): IRxHttp {
        var endIndex = endIndex
        if (endIndex < startIndex) endIndex = -1
        var headerValue = "bytes=$startIndex-"
        if (endIndex >= 0) {
            headerValue += endIndex
        }
        addHeader("RANGE", headerValue)
        if (connectLastProgress) requestBuilder.tag(DownloadOffSize::class.java, DownloadOffSize(startIndex))
        return this
    }

}